<?php
namespace Modules\ShopApi\Models;   
use Illuminate\Support\Facades\DB;
class ShopProductComment extends BaseApiModel
{	
	
	/**
     * @name  关联用户
     */
    public function user_to()
    {
        return $this->belongsTo('Modules\Admin\Models\User','user_id','id');
    }
	/**
     * @name  商品评价列表
     */
	public function product_comments_list($data){
		$list = $this->select('id','content','images','user_id','level','created_at')
				->where('product_id',$data['id'])
				->with([
					'user_to'=>function($query){
						$query->select('id','nick_name','avatar_url','image_id');
					},
					'user_to.image_one'=>function($query){
						$query->select('id','url','open');
					}
				])
				->orderBy('id','desc')
				->paginate(config('shopapi.per_page_product'))
				->toArray();		
		$list['data'] = $this->stt_list($list['data']);
		return $this->api_success(['data'=>[
			'data'			=> $list['data'],
			'last_page'		=> $list['last_page'],
			'per_page'		=> $list['per_page'],
			'current_page'	=> $list['current_page'],
			'total' 		=> $list['total']
		]]);			
	}
	/**
     * @name  商品评价列表数据格式化
     */
	private function stt_list($data){
		$arr = [];
		$http = getHttpType();
		foreach($data as $k=>$v){
			$images = obj_to_arr(DB::table('images')->whereIn('id',explode('|',$v['images']))->select('id','url','open')->get()); 	
			foreach($images as $k1=>$v1){
				if($v1['open'] == 1){
					$images[$k1]['url'] = $http . $v1['url'];
				}else{
					$images[$k1]['url'] = $v1['url'];
				}
			}
			$arr[$k] = [
				'id'=>$v['id'],
				'content'=>$v['content'],
				'created_at'=>$v['created_at'],
				'images'=>$images,
				'nick_name'=>$v['user_to']['nick_name']?sub_str($v['user_to']['nick_name'],1):'***'
			];
			if($v['user_to']['image_id']){
				if($v['user_to']['image_one']['open'] == 1){
					$arr[$k]['image_url'] = getHttpType() . $v['user_to']['image_one']['url'];
				}else{
					$arr[$k]['image_url'] = $v['user_to']['image_one']['url'];
				}
			}else{
				$arr[$k]['image_url'] = $v['user_to']['avatar_url'];
			}
		}
		return $arr;
	}
}
